<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="gNumber">
        <el-input
          v-model="queryParams.gNumber"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联商品" prop="assNumber">
        <el-input
          v-model="queryParams.assNumber"
          placeholder="请输入关联商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brandIds">
        <el-cascader
          v-model="queryParams.brandIds"
          :options="options.brandOptions"
          :props="{ checkStrictly: true }"
          :show-all-levels="false"
          filter clearable
          placeholder="请选择商品品牌"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="类型" prop="typeIds">
        <el-cascader
          v-model="queryParams.typeIds"
          :options="options.gTypeOptions"
          :props="{ checkStrictly: true }"
          :show-all-levels="false"
          filter clearable
          placeholder="请选择商品类型"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择上架状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_goods_sj_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.params.times"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:main:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddGoods"
          v-hasPermi="['goods:main:add']"
        >新增v2</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          plain-->
      <!--          icon="el-icon-sort"-->
      <!--          size="mini"-->
      <!--          @click="toggleExpandAll"-->
      <!--        >展开/折叠</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- <el-table border stripe v-loading="loading" :data="mainList" @selection-change="handleSelectionChange"> -->
    <!-- infinite-scroll-disabled="disabled"  -->
    <el-table
      v-loading="loading"
      v-if="refreshTable"
      border stripe
      :data="mainList"
      row-key="goodsId"
    >
      <!-- :tree-props="{children: 'children', hasChildren: 'hasChildren'}" -->
      <el-table-column label="商品编码" header-align="center" prop="gNumber" width="250" />
      <el-table-column label="商品名称" align="center" prop="goodsName" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <router-link :to="getInfoLink(scope.row)" class="link-type">
            <span>{{ scope.row.goodsName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="封面图" align="center" prop="image" >
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :height="40" />
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" width="150" >
        <template slot-scope="scope">
          <span v-if="scope.row.price" >{{scope.row.price/100}} ￥</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="stockQuantity" />
      <!--      <el-table-column label="操作人" align="center" prop="updateBy" />-->
      <el-table-column label="操作时间" align="center" prop="updateTime" width="160" />
<!--      <el-table-column label="上架状态" align="center" prop="status">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.sys_goods_sj_status" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态" align="center" prop="delFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            style="color: #67c23a"
            v-hasPermi="['goods:main:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:main:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            style="color: #f56c6c"
            v-hasPermi="['goods:main:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品主体信息对话框 -->
    <el-dialog :title="dialogInfo.title" :visible.sync="dialogInfo.open" width="1000px" :close-on-click-modal="false"	>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="关联商品" prop="assNumber">
          <el-input v-model="form.assNumber" placeholder="关联商品编号" disabled/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brandId">
              <treeselect
                v-model="form.brandId"
                :options="options.brandOptions"
                :disabled="isDisabled()"
                placeholder="请选择商品品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="typeId">
              <treeselect
                v-model="form.typeId"
                :options="options.gTypeOptions"
                :disabled="isDisabled()"
                @input="handleTypeInput"
                placeholder="请选择商品类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="gNumber">
              <el-input v-model="form.gNumber" placeholder="商品编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="顺序" prop="orderNum">
              <el-input v-model="form.orderNum" type="number" placeholder="请输入显示顺序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入价格" >
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存" prop="stockQuantity">
              <el-input v-model="form.stockQuantity" type="number" placeholder="请输入库存" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" :disabled="'MOD'==dialogInfo.mode"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="属性分类" >
            <el-transfer
              v-model="form.attrs"
              :data="options.attrOptions"
              target-order="push"
              :titles="['属性列表', '分类列表']"
            >
              <el-button v-if="form.assNumber" class="transfer-footer" slot="right-footer"
                         size="small" type="primary" @click="handleAssort" >获取父分类</el-button>
            </el-transfer>
          </el-form-item>
        </el-row>
        <el-form-item label="封面图片" prop="image">
          <div style="width: 200px; display: inline-grid;">
            <image-upload ref="uploadImage" v-model="form.image" :auto-upload="false" :limit="1"
                          @success="handleImageSuccess" style="width: 500px;" />
          </div>
          <el-button @click="openSelectImage" type="success" plain>选择已上传图片</el-button>
        </el-form-item>
        <el-form-item label="" prop="image">
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上架状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择上架状态">
                <el-option
                  v-for="dict in dict.type.sys_goods_sj_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="delFlag">
              <el-radio-group v-model="form.delFlag">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <select-image ref="select" :params="{ imageType: '1' }" @ok="handleSelectOk" />
  </div>
</template>

<script>
import { listMain, getMain, getMainByGNumber, delMain, addMain, updateMain, findMaxOrderNum } from "@/api/goods/main";
import { treeSelect as optionBrandSelect } from "@/api/goods/brand";
import { treeSelect as optionGTypeSelect } from "@/api/goods/type";
import { typeAttrTreeOptions as optionAttrSelect } from "@/api/goods/attr";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import selectImage from '@/views/goods/images/components/selectImage.vue'

export default {
  name: "Main",
  dicts: ['sys_normal_disable', 'sys_goods_sj_status'],
  components: {
    selectImage,
    Treeselect
  },
  data() {
    // 定义自定义验证函数
    const validatePositiveInteger = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入数字'));
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value)) || Number(value) <= 0) {
          callback(new Error('请输入正整数'));
        } else {
          callback();
        }
      }, 100);
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品主体信息表格数据
      mainList: [],
      // 弹出层信息
      dialogInfo: {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 展示模式
        mode: "",
        // 初次加载
        isInitialized: false,
      },
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assNumber: null,
        gNumber: null,
        goodsName: null,
        brandId: null,
        brandIds: null,
        typeId: null,
        typeIds: null,
        status: null,
        delFlag: null,
        params: {
          times: [],
          startTime: null,
          endTime: null,
        }
      },
      // 下拉列表
      options: {
        brandOptions: [],
        gTypeOptions: [],
        attrOptions: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "商品类型不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" },
          { validator: validatePositiveInteger, trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getBrandTreeSelect();
    this.getGTypeTreeSelect();
    this.getList();
  },
  methods: {
    /** 查询商品品牌下拉树结构 */
    getBrandTreeSelect() {
      optionBrandSelect().then(response => {
        this.options.brandOptions = response.data;
      });
    },
    /** 查询商品类型下拉树结构 */
    getGTypeTreeSelect() {
      optionGTypeSelect().then(response => {
        this.options.gTypeOptions = response.data;
      });
    },
    getAttrTreeOptions(typeId) {
      if (typeId) {
        optionAttrSelect(typeId).then(res => {
          let list = []
          res.data.filter(o => {
            list.push(...this.generateAttrOptions(o))
          })
          this.options.attrOptions = list;
        })
      } else {
        this.options.attrOptions = [];
      }
    },
    generateAttrOptions(options) {
      let list = []
      if (options) {
        if (options.children) {
          list.push({key: options.id+'', label: options.label, disabled: true})
          options.children.filter(c => {
            list.push(...this.generateAttrOptions(c));
          })
        } else {
          list.push({key: options.id+'', label: options.label, disabled: options.disabled})
        }
      }
      return list
    },
    /** 查询商品主体信息列表 */
    getList() {
      this.loading = true;
      let queryParams =  this.queryParams;
      if (queryParams.params.times && queryParams.params.times.length === 2) {
        queryParams.params.startTime = queryParams.params.times[0];
        queryParams.params.endTime = queryParams.params.times[1];
      }
      listMain(queryParams).then(response => {
        // this.mainList = this.handleTree(response.rows, "goodsId", "parentId");
        this.mainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.dialogInfo.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        assNumber: null,
        gNumber: null,
        goodsName: null,
        brandId: null,
        typeId: null,
        price: 0,
        stockQuantity: 0,
        image: null,
        orderNum: null,
        status: '0',
        delFlag: '0',
        remark: null,
        assort: null,// 分类
        attrs: [],
      };
      // this.options.attrOptions = [];
      // this.$refs["form"].resetFields();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.brandId = this.getLastValueByArray(this.queryParams.brandIds)
      this.queryParams.typeId = this.getLastValueByArray(this.queryParams.typeIds)
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 获取最后一个值 */
    getLastValueByArray(ids) {
      if (ids && ids.length > 0) {
        return ids[ids.length-1];
      } else {
        return null;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.params = {
        times: [],
        startTime: null,
        endTime: null,
      };
      this.handleQuery();
    },
    handleAddGoods() {
      this.$router.push('/goods/info/add');
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      let assNumber = null;
      if (row && row.goodsId) {
        assNumber = row.assNumber? row.assNumber : row.gNumber;
        this.dialogInfo.isInitialized = true;
      } else {
        this.dialogInfo.isInitialized = false;
      }
      findMaxOrderNum(assNumber).then(res => {
        const num = res.data;
        this.form.orderNum = num;
        if (assNumber) {
          this.form.assNumber = assNumber;
          this.form.brandId = row.brandId;
          this.form.typeId = row.typeId;
          this.form.goodsName = row.goodsName;
          this.form.assort = row.assort;
          this.dialogInfo.mode = 'ADD';
          this.getAttrTreeOptions(row.typeId);
        } else {
          this.dialogInfo.mode = 'NEW';
          this.getAttrTreeOptions();
        }
        this.dialogInfo.open = true;
        this.dialogInfo.title = "添加商品主体信息";
      })
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.dialogInfo.mode = 'MOD';
      this.getAttrTreeOptions(row.typeId);
      await getMain(row.goodsId).then(res => {
        let main = res.data;
        if (main.assort) {
          main.attrs = main.assort.split(',');
        }
        this.form = main;
        this.dialogInfo.title = "修改商品主体信息";
        this.dialogInfo.isInitialized = true;
        this.dialogInfo.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attrs) {
            this.form.assort = this.listToString(this.form.attrs);
          } else {
            this.form.assort = ''
          }
          // 上传蹄片
          if (!this.form.image) {
            this.form.imageId = null;
            let files = this.$refs.uploadImage.$refs.imageUpload.uploadFiles; // 获取选中的文件列表
            if (files && files.length > 0) {
              this.$refs.uploadImage.$refs.imageUpload.submit(); // 手动调用上传
            } else {
              this.$modal.msgError("请先选择图片");
            }
          } else {
            this.submitMainForm();
          }
        }
      });
    },
    submitMainForm() {
      if (this.form.goodsId != null) {
        updateMain(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.dialogInfo.open = false;
          this.getList();
        });
      } else {
        addMain(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.dialogInfo.open = false;
          this.getList();
        });
      }
    },
    handleImageSuccess(fileList) {
      this.submitMainForm()
    },
    isEmpty(val) {
      if (val == null || val === '' || val === undefined) {
        return true;
      }
      return false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let _this = this;
      this.$modal.confirm('是否确认删除商品编码为" ' + row.gNumber + ' "的数据项？')
        .then(function() {
          if (_this.isEmpty(row.assNumber) || row.gNumber === row.assNumber) {
            _this.$modal.confirm(row.gNumber + " 有关联商品，是否删除所有关联商品？")
              .then(function() {
                delMain(row.gNumber).then(() => {
                  _this.getList();
                  _this.$modal.msgSuccess("删除成功");
                })
              })
          } else {
            delMain(row.gNumber).then(() => {
              _this.getList();
              _this.$modal.msgSuccess("删除成功");
            })
          }
        })
      // let configMsg = '';
      // if (this.isEmpty(row.assNumber) || row.gNumber === row.assNumber) {
      //   configMsg = row.gNumber + " 有关联商品，是否删除所有关联商品？"
      // } else {
      //   configMsg = '是否确认删除商品编码为" ' + row.gNumber + ' "的数据项？'
      // }
      // this.$modal.confirm(configMsg).then(function() {
      //   return delMain(row.gNumber);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/main/export', {
        ...this.queryParams
      }, `main_${new Date().getTime()}.xlsx`)
    },
    // 弹出层是否禁用
    isDisabled() {
      if ('NEW' == this.dialogInfo.mode) {
        return false;
      } else {
        return true;
      }
    },
    // 输入判断
    handleInput() {
      if (!this.form.price || this.form.price <= 0) {
        this.form.price = 0;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i] + separator;
      }
      return strs != '' ? strs.substring(0, strs.length - 1) : '';
    },
    handleTypeInput(val) {
      if (this.dialogInfo.isInitialized) {
        this.dialogInfo.isInitialized = false;
      } else {
        this.form.attrs = []
        this.getAttrTreeOptions(val);
      }
    },
    handleAssort() {
      this.form.attrs = []
      if (this.form.assNumber) {
        getMainByGNumber(this.form.assNumber).then(res => {
          if (res.data && res.data.assort) {
            this.form.attrs = res.data.assort.split(',');
          }
        })
      }
    },
    getInfoLink(row) {
      let to = {
        path: '/goods/info/index/' + row.gNumber,
        query: { name: row.goodsName }
      }
      return to;
    },
    /** 打开授权用户表弹窗 */
    openSelectImage() {
      this.$refs.select.show();
    },
    /** 选择图片后 */
    handleSelectOk(val) {
      if (val && val.length === 1) {
        const image = val[0];
        this.form.imageId = image.imageId;
        this.form.image = image.imagePath;
      }
    }
  }
};
</script>
<style scoped>
::v-deep .el-table .el-table__body-wrapper .el-table__cell {
  padding: 5px 0 2px 0;
}
</style>
<!-- <style scoped>
::v-deep .el-table {
  .el-table__row--level-0 .cell{
    padding-left: 0;
  }
  .el-table__row--level-1 .cell{
    padding-left: 6px;

    .el-table__placeholder {
      width: 0;
    }
  }
}
</style> -->
